package com.study.service.impl;

import com.study.exception.ServiceException;
import com.study.model.dto.ImageVerifyCodeRespDto;
import com.study.service.ImageVerifyCodeService;
import com.study.util.ImageVerifyCode;
import com.study.util.SysConst;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

@Slf4j
@Service
public class ImageVerifyCodeServiceImpl implements ImageVerifyCodeService {
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public ImageVerifyCodeRespDto generatorImage() {
        ImageVerifyCode imageVerifyCode = new ImageVerifyCode();

        BufferedImage bufferedImage = imageVerifyCode.getImage();
        String text = imageVerifyCode.getText();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ImageVerifyCode.output(bufferedImage, outputStream);
            byte[] bytes = outputStream.toByteArray();
            outputStream.flush();
            outputStream.close();

            String imageStr = "data:image/jpg;base64," + Base64.encodeBase64String(bytes);

            String uuid = UUID.randomUUID().toString().replace("-", "");
            RBucket<String> rBucket = redissonClient.getBucket(SysConst.RedisPrefix.IMAGE_VERIFY_CODE + uuid);
            rBucket.set(text, 10, TimeUnit.MINUTES);

            log.info("生成验证码{}成功",text);
            return new ImageVerifyCodeRespDto(uuid,imageStr);
        } catch (IOException e) {
            throw new ServiceException("验证码生成错误", e);
        }
    }
}
